package servlets;

import dao.DrugDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Сервлет, используемый для поиска записей
 *
 * @author Andrey Murgo
 */
public class SearchController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Получение параметров
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String substance = req.getParameter("substance");
        String farmaaction = req.getParameter("farmaaction");
        String minRub = req.getParameter("minRub");
        String minCop = req.getParameter("minCop");
        String maxRub = req.getParameter("maxRub");
        String maxCop = req.getParameter("maxCop");
        //Создание объекта, хранящего параметры поиска
        DrugDAO.DrugParam param = new DrugDAO.DrugParam();
        if (isValidParam(id)) {
            param.setId(Integer.parseInt(id));
        }
        if (isValidParam(name)) {
            param.setDrugName(name.trim());
        }
        if (isValidParam(substance)) {
            param.setSubstance(substance.trim());
        }
        if (isValidParam(farmaaction)) {
            param.setFarmaaction(farmaaction.trim());
        }
        //Т.к. цена состоит из двух полей
        if (isValidParam(minRub) || isValidParam(minCop)) {
            param.setMinCost(
                    Double.parseDouble(minRub + "." + minCop)
            );
        }
        if (isValidParam(maxRub) || isValidParam(maxCop)) {
            param.setMaxCost(
                    Double.parseDouble(maxRub + "." + maxCop)
            );
        }
        //Передача объекта сервлету, отвечающему за отображение результатов
        req.setAttribute("searchParam", param);
        req.setAttribute("previousEvent", "search");
        req.getRequestDispatcher("view.do").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private boolean isValidParam(String param) {
        return (param != null && !param.isEmpty());
    }
}
